package com.guldan.jaina.manager;

import com.guldan.core.constants.CommonConstant;
import com.guldan.core.enums.GRoleTypeEn;
import com.guldan.core.enums.ProjectRegisterBatchEn;
import com.guldan.core.enums.ProjectRegisterEn;
import com.guldan.core.manager.BaseManager;
import com.guldan.core.utils.DateUtil;
import com.guldan.core.utils.MathUtil;
import com.guldan.jaina.dto.area.AreaDTO;
import com.guldan.jaina.dto.datastat.datav.DatavDTO;
import com.guldan.jaina.dto.datastat.datav.MetaDTO;
import com.guldan.jaina.dto.datastat.home.BatchRegistStatDTO;
import com.guldan.jaina.dto.datastat.home.HotProjectStatDTO;
import com.guldan.jaina.dto.datastat.home.Part1DTO;
import com.guldan.jaina.dto.datastat.home.Part2DTO;
import com.guldan.jaina.dto.datastat.report.MoneyStatDTO;
import com.guldan.jaina.dto.datastat.report.ReportSearchDTO;
import com.guldan.jaina.dto.datastat.report.SubsidyGrantStatDTO;
import com.guldan.jaina.dto.report.Point;
import com.guldan.jaina.dto.report.Points;
import com.guldan.jaina.dto.report.project.ProjectSearchDTO;
import com.guldan.jaina.utils.UserUtils;
import com.guldan.mapper.db.entity.*;
import com.guldan.mapper.db.mapper.*;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by Silas.
 * Date: 2016/12/11
 * Time: 22:52
 */

@Service
public class ReportManager extends BaseManager {


    @Autowired
    private DataStatMapper dataStatMapper;

    @Autowired
    private ProjectManager projectManager;

    @Autowired
    private AreaManager areaManager;

    @Autowired
    private ProjectCategoryManager projectCategoryManager;


    public List<Points> projectMoneyStat(ProjectSearchDTO searchDTO) {

        List<Points> pointsList = new ArrayList<>();

        Points points = new Points();
        points.setName("项目1");
        List<Point> pointList = new ArrayList<>();
        pointList.add(new Point("1月", 1000.0));
        pointList.add(new Point("2月", 2000.1));
        pointList.add(new Point("3月", 3000.33));
        pointList.add(new Point("4月", 222.0));
        pointList.add(new Point("5月", 433.5));
        points.setPointList(pointList);

        points = new Points();
        points.setName("项目2");
        pointList = new ArrayList<>();
        pointList.add(new Point("1月", 1000.0));
        pointList.add(new Point("2月", 2000.1));
        pointList.add(new Point("3月", 3000.33));
        pointList.add(new Point("4月", 222.0));
        pointList.add(new Point("5月", 433.5));
        points.setPointList(pointList);


        pointsList.add(points);

        return pointsList;
    }


    public Part1DTO getPart1DTO() {

        int projectNumState = 0;
        int treatingNumStateBegin = 0;
        int treatingNumStateEnd = 0;

        String projectNumStr = "登记项目数", treatingNumStr = "在途发放人次", successNumStr = "发放成功人次", successMoneyStr = "发放成功金额";

        List<Integer> areaIds = (List<Integer>) cacheService.getCache(String.format(CommonConstant.KEY_AREA, UserUtils.getUser().getAreaId()));

        if (areaIds == null || areaIds.size() == 0) {
            areaIds = new ArrayList<>();
        }
        areaIds.add(UserUtils.getUser().getAreaId());

        switch (UserUtils.getUser().getUserRole()) {
            case CommonConstant.ROLE_TownsEntry:
                projectNumState = 0;
                treatingNumStateBegin = ProjectRegisterEn.auditor_ing.getCode();
                treatingNumStateEnd = ProjectRegisterEn.finance_downloaded_file.getCode();
                projectNumStr = "登记项目数";
                break;
            case CommonConstant.ROLE_TownsReview:
                projectNumState = 0;
                treatingNumStateBegin = ProjectRegisterEn.org_auditor_ing.getCode();
                treatingNumStateEnd = ProjectRegisterEn.finance_downloaded_file.getCode();
                projectNumStr = "登记项目数";
                break;
            case CommonConstant.ROLE_Org:
                projectNumState = ProjectRegisterEn.org_auditor_ed.getCode();
                treatingNumStateBegin = ProjectRegisterEn.org_auditor_ed.getCode();
                treatingNumStateEnd = ProjectRegisterEn.finance_downloaded_file.getCode();
                projectNumStr = "审批项目数";
                break;
            case CommonConstant.ROLE_Finance:
                projectNumState = ProjectRegisterEn.finance_auditor_ed.getCode();
                treatingNumStateBegin = ProjectRegisterEn.finance_auditor_ed.getCode();
                treatingNumStateEnd = ProjectRegisterEn.finance_downloaded_file.getCode();
                projectNumStr = "审批项目数";
                break;
            default:
                break;
        }

        Part1DTO part1DTO = dataStatMapper.getPart1DTO(projectNumState, treatingNumStateBegin, treatingNumStateEnd, areaIds);

        part1DTO.setProjectNumStr(projectNumStr);
        part1DTO.setTreatingNumStr(treatingNumStr);
        part1DTO.setSuccessMoneyStr(successMoneyStr);
        part1DTO.setSuccessNumStr(successNumStr);

        return part1DTO;
    }

    public Part2DTO getPart2DTO() {

        int todoNumState = 0;
        int treatingAuditorNumStateBegin = 0;
        int treatingAuditorNumStateEnd = 0;

        String todoNumStr = "待上报", treatingAuditorNumStr = "在途发放", allSuccessNumStr = "全部成功", partSuccessNumStr = "部分成功", grantingSuccessRateStr = "发放完成率";

        List<Integer> areaIds = (List<Integer>) cacheService.getCache(String.format(CommonConstant.KEY_AREA, UserUtils.getUser().getAreaId()));

        if (areaIds == null || areaIds.size() == 0) {
            areaIds = new ArrayList<>();
        }
        areaIds.add(UserUtils.getUser().getAreaId());

        switch (UserUtils.getUser().getUserRole()) {
            case CommonConstant.ROLE_TownsEntry:
                todoNumState = ProjectRegisterBatchEn.register_ing.getCode();
                treatingAuditorNumStateBegin = ProjectRegisterBatchEn.auditor_ing.getCode();
                treatingAuditorNumStateEnd = ProjectRegisterBatchEn.finance_downloaded_file.getCode();

                todoNumStr = "待上报";

                break;
            case CommonConstant.ROLE_TownsReview:
                todoNumState = ProjectRegisterBatchEn.auditor_ing.getCode();
                treatingAuditorNumStateBegin = ProjectRegisterBatchEn.auditor_ed.getCode();
                treatingAuditorNumStateEnd = ProjectRegisterBatchEn.finance_downloaded_file.getCode();

                todoNumStr = "待复核";
                break;
            case CommonConstant.ROLE_Org:
                todoNumState = ProjectRegisterBatchEn.org_auditor_ing.getCode();
                treatingAuditorNumStateBegin = ProjectRegisterBatchEn.org_auditor_ed.getCode();
                treatingAuditorNumStateEnd = ProjectRegisterBatchEn.finance_downloaded_file.getCode();

                todoNumStr = "待审批";
                break;
            case CommonConstant.ROLE_Finance:
                todoNumState = ProjectRegisterBatchEn.finance_auditor_ing.getCode();
                treatingAuditorNumStateBegin = ProjectRegisterBatchEn.finance_auditor_ed.getCode();
                treatingAuditorNumStateEnd = ProjectRegisterBatchEn.finance_downloaded_file.getCode();

                todoNumStr = "待审批";
                break;
            default:
                break;
        }

        Part2DTO part2DTO = dataStatMapper.getPart2DTO(todoNumState, treatingAuditorNumStateBegin, treatingAuditorNumStateEnd, areaIds);

        if (part2DTO != null) {
            int p1 = part2DTO.getAllSuccessNum() + part2DTO.getPartSuccessNum();
            int p2 = part2DTO.getAllSuccessNum() + part2DTO.getPartSuccessNum() + part2DTO.getTreatingAuditorNum();
            BigDecimal r = new BigDecimal(0.00);
            if (p2 != 0 && p1 != 0) {
                r = MathUtil.divide(new BigDecimal(p1), p2, 2, BigDecimal.ROUND_HALF_UP);
            }
            part2DTO.setGrantingSuccessRate(r.doubleValue());
        } else part2DTO = new Part2DTO();

        part2DTO.setTodoNumStr(todoNumStr);
        part2DTO.setTreatingAuditorNumStr(treatingAuditorNumStr);
        part2DTO.setAllSuccessNumStr(allSuccessNumStr);
        part2DTO.setPartSuccessNumStr(partSuccessNumStr);
        part2DTO.setGrantingSuccessRateStr(grantingSuccessRateStr);

        return part2DTO;
    }

    public List<BatchRegistStatDTO> getBatchRegistStatByDate(Integer searchType, String dateBegin, String dateEnd) {

        int rsStateBegin = 0;
        int rsStateNotEqual = 0;
        int prbStateBegin = 0;


        List<Integer> areaIds = (List<Integer>) cacheService.getCache(String.format(CommonConstant.KEY_AREA, UserUtils.getUser().getAreaId()));

        if (areaIds == null || areaIds.size() == 0) {
            areaIds = new ArrayList<>();
        }
        areaIds.add(UserUtils.getUser().getAreaId());

        switch (UserUtils.getUser().getUserRole()) {
            case CommonConstant.ROLE_TownsEntry:
                rsStateBegin = ProjectRegisterEn.auditor_ing.getCode();
                rsStateNotEqual = -1;
                prbStateBegin = ProjectRegisterBatchEn.auditor_ing.getCode();
                break;
            case CommonConstant.ROLE_TownsReview:
                rsStateBegin = ProjectRegisterEn.auditor_ed.getCode();
                rsStateNotEqual = ProjectRegisterEn.auditor_fail.getCode();
                prbStateBegin = ProjectRegisterBatchEn.auditor_ed.getCode();
                break;
            case CommonConstant.ROLE_Org:
                rsStateBegin = ProjectRegisterEn.org_auditor_ed.getCode();
                rsStateNotEqual = ProjectRegisterEn.org_auditor_fail.getCode();
                prbStateBegin = ProjectRegisterBatchEn.org_auditor_ed.getCode();
                break;
            case CommonConstant.ROLE_Finance:
                rsStateBegin = ProjectRegisterEn.finance_auditor_ed.getCode();
                rsStateNotEqual = ProjectRegisterEn.finance_auditor_fail.getCode();
                prbStateBegin = ProjectRegisterBatchEn.finance_auditor_ed.getCode();
                break;
            default:
                break;
        }

        List<BatchRegistStatDTO> list = new ArrayList<>();

        list = dataStatMapper.getBatchRegistStatByDate(rsStateBegin, rsStateNotEqual, prbStateBegin, dateBegin, dateEnd, areaIds);

        return list;
    }

    public List<HotProjectStatDTO> getHotProjectStatList() {

        int rsStateBegin = 0;
        int rsStateNotEqual = 0;
        int rowCount = 5;

        List<Integer> areaIds = (List<Integer>) cacheService.getCache(String.format(CommonConstant.KEY_AREA, UserUtils.getUser().getAreaId()));

        if (areaIds == null || areaIds.size() == 0) {
            areaIds = new ArrayList<>();
        }
        areaIds.add(UserUtils.getUser().getAreaId());

        switch (UserUtils.getUser().getUserRole()) {
            case CommonConstant.ROLE_TownsEntry:
                rsStateBegin = ProjectRegisterEn.auditor_ing.getCode();
                rsStateNotEqual = 0;
                break;
            case CommonConstant.ROLE_TownsReview:
                rsStateBegin = ProjectRegisterEn.auditor_ed.getCode();
                rsStateNotEqual = ProjectRegisterEn.auditor_fail.getCode();
                break;
            case CommonConstant.ROLE_Org:
                rsStateBegin = ProjectRegisterEn.org_auditor_ed.getCode();
                rsStateNotEqual = ProjectRegisterEn.org_auditor_fail.getCode();
                break;
            case CommonConstant.ROLE_Finance:
                rsStateBegin = ProjectRegisterEn.bank_success.getCode();
                rsStateNotEqual = ProjectRegisterEn.bank_fail.getCode();
                break;
            default:
                break;
        }


        List<HotProjectStatDTO> list = dataStatMapper.getHotProjectStatList(rsStateBegin, rsStateNotEqual, rowCount, areaIds);

        if (list == null) list = new ArrayList<>();
        return list;
    }


    //数据可视化
    //补贴发放统计

    //金额统计
    public List<MoneyStatDTO> getMoneyStat(ReportSearchDTO searchDTO) {
        buildSearch(searchDTO);
        List<MoneyStatDTO> list = dataStatMapper.getMoneyStat(searchDTO.getDateBegin(), searchDTO.getDateEnd(), searchDTO.getAreaIds(), searchDTO.getProjectIds(), searchDTO.getStates());
        return list;
    }

    //人次统计
    public List<SubsidyGrantStatDTO> getPersonStat(ReportSearchDTO searchDTO) {
        buildSearch(searchDTO);
        //date_str,person_total,person_count
        List<SubsidyGrantStatDTO> list = dataStatMapper.getPersonStat(searchDTO.getDateBegin(), searchDTO.getDateEnd(), searchDTO.getAreaIds(), searchDTO.getProjectIds(), searchDTO.getStates());
        return list;
    }

    //发放情况统计-按区划(柱状+折线)
    public List<SubsidyGrantStatDTO> getSubsidyGrantStatForArea(ReportSearchDTO searchDTO) {
        List<Integer> areaIds = new ArrayList<>(searchDTO.getAreaIds());
        buildSearch(searchDTO);

        List<SubsidyGrantStatDTO> list = new ArrayList<>();

        //重新设置筛选区划
        if (areaIds != null && areaIds.size() > 0) {
            areaIds = areaManager.getChildrenAreaIds(areaIds.get(0), false);
            if (areaIds != null && areaIds.size() > 0) {
                for (Integer aid : areaIds) {
                    List<Integer> aids = (List<Integer>) cacheService.getCache(String.format(String.format(CommonConstant.KEY_AREA, aid)));
                    if (aids == null) aids = new ArrayList<>();
                    aids.add(aid);

                    //money_total,person_total,person_count
                    List<SubsidyGrantStatDTO> listTemp = dataStatMapper.getSubsidyGrantStatForArea(searchDTO.getDateBegin(), searchDTO.getDateEnd(), aids, searchDTO.getProjectIds(), searchDTO.getStates());
                    SubsidyGrantStatDTO tempDto = listTemp.get(0);


                    Area area = (Area) cacheService.getCache(String.format(CommonConstant.KEY_AREA_DATA, aid));
                    tempDto.setAreaStr(area.getAreaName());

                    list.add(tempDto);
                }
            }
        }

        return list;
    }

    //发放情况统计-按项目(柱状+折线)
    public List<SubsidyGrantStatDTO> getSubsidyGrantStatForProject(ReportSearchDTO searchDTO) {
        buildSearch(searchDTO);

        //project_str,money_total,person_total,person_count
        List<SubsidyGrantStatDTO> list = dataStatMapper.getSubsidyGrantStatForProject(searchDTO.getDateBegin(), searchDTO.getDateEnd(), searchDTO.getAreaIds(), searchDTO.getProjectIds(), searchDTO.getStates());
        return list;
    }

    //覆盖人次性别统计
    public List<SubsidyGrantStatDTO> getGenderStat(ReportSearchDTO searchDTO) {
        buildSearch(searchDTO);

        //gender_str,person_total
        List<SubsidyGrantStatDTO> list = dataStatMapper.getGenderStat(searchDTO.getDateBegin(), searchDTO.getDateEnd(), searchDTO.getAreaIds(), searchDTO.getProjectIds(), searchDTO.getStates());
        return list;
    }

    //覆盖人次民族统计
    public List<SubsidyGrantStatDTO> getNationStat(ReportSearchDTO searchDTO) {
        buildSearch(searchDTO);
        List<SubsidyGrantStatDTO> list = new ArrayList<>();
        //nation_str,person_total
        List<SubsidyGrantStatDTO> oriList = dataStatMapper.getNationStat(searchDTO.getDateBegin(), searchDTO.getDateEnd(), searchDTO.getAreaIds(), searchDTO.getProjectIds(), searchDTO.getStates());

        if (oriList.size() > 5) {
            for (int i = 0; i < 5; i++) {
                list.add(oriList.get(i));
            }
            int total = 0;
            for (int i = 5; i < oriList.size(); i++) {
                total += oriList.get(i).getPersonTotal();
            }
            SubsidyGrantStatDTO over5 = new SubsidyGrantStatDTO();
            over5.setNationStr("其他");
            over5.setPersonTotal(total);
            list.add(over5);
        } else {
            list = oriList;
        }
        return list;
    }


    //受益年龄统计
    public List<SubsidyGrantStatDTO> getBenefitAgeStat(ReportSearchDTO searchDTO) {
        buildSearch(searchDTO);

        List<SubsidyGrantStatDTO> list = new ArrayList<>();

        //age_str,age_flag,person_total
        List<SubsidyGrantStatDTO> oriList = dataStatMapper.getBenefitAgeStat(searchDTO.getDateBegin(), searchDTO.getDateEnd(), searchDTO.getAreaIds(), searchDTO.getProjectIds(), searchDTO.getStates());

        for (int i = 0; i < 10; i++) {
            list.add(oriList.get(i));
        }
        int total = 0;
        for (int i = 10; i < oriList.size(); i++) {
            total += oriList.get(i).getPersonTotal();
        }
        SubsidyGrantStatDTO over100 = new SubsidyGrantStatDTO();
        over100.setAgeStr("100岁以上");
        over100.setAgeFlag(10);
        over100.setPersonTotal(total);
        list.add(over100);
        return list;
    }


    //##人员信息统计
    //性别统计
    public List<SubsidyGrantStatDTO> getGenderStatForCitzen(ReportSearchDTO searchDTO) {

        buildAreaSearch(searchDTO);

        //gender_str,person_total
        List<SubsidyGrantStatDTO> list = dataStatMapper.getGenderStatForCitzen(searchDTO.getAreaIds());
        return list;
    }

    //年龄结构统计
    public List<SubsidyGrantStatDTO> getAgeStatForCitzen(ReportSearchDTO searchDTO) {

        buildAreaSearch(searchDTO);
        List<SubsidyGrantStatDTO> list = new ArrayList<>();
        //age_str,age_flag,person_total
        List<SubsidyGrantStatDTO> oriList = dataStatMapper.getAgeStatForCitzen(searchDTO.getAreaIds());
        for (int i = 0; i < 10; i++) {
            list.add(oriList.get(i));
        }
        int total = 0;
        for (int i = 10; i < oriList.size(); i++) {
            total += oriList.get(i).getPersonTotal();
        }
        SubsidyGrantStatDTO over100 = new SubsidyGrantStatDTO();
        over100.setAgeStr("100岁以上");
        over100.setAgeFlag(10);
        over100.setPersonTotal(total);
        list.add(over100);
        return list;
    }

    //民族统计
    public List<SubsidyGrantStatDTO> getNationStatForCitzen(ReportSearchDTO searchDTO) {

        buildAreaSearch(searchDTO);

        List<SubsidyGrantStatDTO> list = new ArrayList<>();

        //nation_str,person_count
        List<SubsidyGrantStatDTO> oriList = dataStatMapper.getNationStatForCitzen(searchDTO.getAreaIds());

        if (oriList.size() > 5) {
            for (int i = 0; i < 5; i++) {
                list.add(oriList.get(i));
            }
            int count = 0;
            for (int i = 5; i < oriList.size(); i++) {
                count += oriList.get(i).getPersonCount();
            }
            SubsidyGrantStatDTO over5 = new SubsidyGrantStatDTO();
            over5.setNationStr("其他");
            over5.setPersonCount(count);
            list.add(over5);
        } else {
            list = oriList;
        }

        return list;
    }

    //区划人数
    public List<SubsidyGrantStatDTO> getAreaPersonStatForCitzen(ReportSearchDTO searchDTO) {
        List<Integer> areaIds = new ArrayList<>(searchDTO.getAreaIds());
        buildSearch(searchDTO);

        List<SubsidyGrantStatDTO> list = new ArrayList<>();

        //重新设置筛选区划
        if (areaIds != null && areaIds.size() > 0) {
            areaIds = areaManager.getChildrenAreaIds(areaIds.get(0), false);
            if (areaIds != null && areaIds.size() > 0) {
                for (Integer aid : areaIds) {
                    List<Integer> aids = (List<Integer>) cacheService.getCache(String.format(String.format(CommonConstant.KEY_AREA, aid)));
                    if (aids == null) aids = new ArrayList<>();
                    aids.add(aid);

                    //person_count 人数
                    List<SubsidyGrantStatDTO> listTemp = dataStatMapper.getAreaPersonStatForCitzen(aids);
                    SubsidyGrantStatDTO tempDto = listTemp.get(0);


                    Area area = (Area) cacheService.getCache(String.format(CommonConstant.KEY_AREA_DATA, aid));
                    tempDto.setAreaStr(area.getAreaName());

                    list.add(tempDto);
                }
            }
        }

        return list;
    }


    //获取datav数据
    public DatavDTO getDatavDTO(String divisionCode, Boolean fromCache) {
        AreaDTO areaDTO = areaManager.getByDivisionCode(divisionCode);
        return getDatavDTO2(areaDTO.getAreaId(), fromCache);
    }


    public DatavDTO getDatavDTO(Integer areaId, Boolean fromCache) {


        if (fromCache)
            try {
                Object cacheDatavDTO = cacheService.getCache(String.format(CommonConstant.KEY_DATAV_AREA_DATA, areaId));
                logger.info(JSONObject.fromObject(cacheDatavDTO).toString());
                if (cacheDatavDTO != null) {
                    return (DatavDTO) cacheDatavDTO;
                }
            } catch (Exception ex) {
                logger.info("put datav to redis fail, areaId %s", areaId);
            }


        DatavDTO datavDTO = new DatavDTO();

        datavDTO.setAreaId(areaId);
        datavDTO.setBegin(DateUtil.getYear(DateUtil.getCurrentTime()) + "-01-01");
        datavDTO.setEnd(DateUtil.toLocaleString(DateUtil.getCurrentTime(), DateUtil.DEFAULT_DATE_FORMAT));

        List<Integer> areaIdsWithChild = (List<Integer>) cacheService.getCache(String.format(CommonConstant.KEY_AREA, areaId));
        if (areaIdsWithChild == null || areaIdsWithChild.size() == 0) {
            areaIdsWithChild = new ArrayList<>();
        }
        areaIdsWithChild.add(areaId);

        //顶部实时发放人次，实时发放金额
        MetaDTO m1 = dataStatMapper.datav_getMoney(datavDTO.getBegin(), datavDTO.getEnd(), areaIdsWithChild);
        datavDTO.setGrantTotal(m1.getGrantTotal());
        datavDTO.setGrantMoney(m1.getGrantMoney());

        //第一排，左侧发放项目关键词(即首页热门排行)
        List<MetaDTO> metaDTOList1 = dataStatMapper.datav_getHotProjectList(datavDTO.getBegin(), datavDTO.getEnd(), areaIdsWithChild);
        datavDTO.setProjectRank(metaDTOList1);

        //第一排，右侧区划统计
        List<MetaDTO> areaData = new ArrayList<>();
        List<Integer> areaIds = areaManager.getChildrenAreaIds(areaId, false); //获取需要统计区划下一级的区划id列表
        if (areaIds != null && areaIds.size() > 0) {
            for (Integer aid : areaIds) {
                List<Integer> aids = (List<Integer>) cacheService.getCache(String.format(CommonConstant.KEY_AREA, aid));
                if (aids == null || aids.size() == 0) {
                    aids = new ArrayList<>();
                }
                aids.add(aid);

                MetaDTO metaDTO = dataStatMapper.datav_getMoney(datavDTO.getBegin(), datavDTO.getEnd(), aids);
                metaDTO.setAreaId(aid);
                Area areaEntity = (Area) cacheService.getCache(String.format(CommonConstant.KEY_AREA_DATA, aid));
                metaDTO.setAreaStr(areaEntity.getAreaName());
                if (areaEntity != null && org.apache.commons.lang.StringUtils.isNotBlank(areaEntity.getDivisionCode()))
                    metaDTO.setDivisionCode(areaEntity.getDivisionCode());
                areaData.add(metaDTO);
            }
        }
        datavDTO.setAreaData(areaData);

        //第二排，左侧，受益人群年龄占比

        List<MetaDTO> ageData = new ArrayList<>();

        List<MetaDTO> oriAgeData = dataStatMapper.datav_getBenefitAgeStat(datavDTO.getBegin(), datavDTO.getEnd(), areaIdsWithChild);


        for (int i = 0; i < 10; i++) {
            ageData.add(oriAgeData.get(i));
        }
        int total = 0;
        for (int i = 10; i < oriAgeData.size(); i++) {
            total += oriAgeData.get(i).getGrantTotal();
        }
        MetaDTO over100 = new MetaDTO();
        over100.setAgeStr("100岁以上");
        over100.setAgeFlag(10);
        over100.setGrantTotal(total);
        ageData.add(over100);

        datavDTO.setAgeData(ageData);

        //第二排，中间，当前发放情况
        List<MetaDTO> monthData = dataStatMapper.datav_getMoneyGroupByMonth(areaIdsWithChild);
        datavDTO.setMonthData(monthData);

        //第二排，右侧，受益人群，性别占比
        List<MetaDTO> genderData = dataStatMapper.datav_getGenderStat(datavDTO.getBegin(), datavDTO.getEnd(), areaIdsWithChild);
        datavDTO.setGenderData(genderData);

        return datavDTO;
    }

    public DatavDTO getDatavDTO2(Integer areaId, Boolean fromCache) {
        if (fromCache)
            try {
                Object cacheDatavDTO = cacheService.getCache(String.format(CommonConstant.KEY_DATAV_AREA_DATA, areaId));
                logger.info(JSONObject.fromObject(cacheDatavDTO).toString());
                if (cacheDatavDTO != null) {
                    return (DatavDTO) cacheDatavDTO;
                }
            } catch (Exception ex) {
                logger.info("put datav to redis fail, areaId %s", areaId);
            }


        DatavDTO datavDTO = new DatavDTO();

        datavDTO.setAreaId(areaId);
        datavDTO.setBegin(DateUtil.getYear(DateUtil.getCurrentTime()) + "-01-01");
        datavDTO.setEnd(DateUtil.toLocaleString(DateUtil.getCurrentTime(), DateUtil.DEFAULT_DATE_FORMAT));

        List<Integer> areaIdsWithChild = (List<Integer>) cacheService.getCache(String.format(CommonConstant.KEY_AREA, areaId));
        if (areaIdsWithChild == null || areaIdsWithChild.size() == 0) {
            areaIdsWithChild = new ArrayList<>();
        }
        areaIdsWithChild.add(areaId);

        //顶部实时发放人次，实时发放金额
        MetaDTO m1 = dataStatMapper.datav_getMoney(datavDTO.getBegin(), datavDTO.getEnd(), areaIdsWithChild);
        datavDTO.setGrantTotal(m1.getGrantTotal());
        datavDTO.setGrantMoney(m1.getGrantMoney());

        //第一排，左侧区划，按年汇总统计
        int nowYear = DateUtil.getYear(DateUtil.getCurrentTime());
        int beginYear = 2015;
        List<Points> areaYearData = new ArrayList<>();
        while (beginYear <= nowYear) {
            List<MetaDTO> metaDTOList1 = dataStatMapper.datav_getAreaYearDataByYear(beginYear);
            Points points = new Points();
            points.setName(String.valueOf(beginYear));
            List<Point> list = new ArrayList<>();
            if (metaDTOList1 != null) {
                for (MetaDTO metaDTO : metaDTOList1) {
                    list.add(new Point(metaDTO.getAreaStr(), metaDTO.getGrantMoney().doubleValue()));
                }
                points.setPointList(list);
            }
            beginYear++;
            areaYearData.add(points);
        }
        datavDTO.setAreaYearData(areaYearData);
//        List<MetaDTO> metaDTOList1 = dataStatMapper.datav_getAreaYearDataByYear(datavDTO.getBegin(), datavDTO.getEnd(), areaIdsWithChild);
//        datavDTO.setProjectRank(metaDTOList1);

        //第一排，右侧区划统计
        List<MetaDTO> areaData = new ArrayList<>();
        List<Integer> areaIds = areaManager.getChildrenAreaIds(areaId, false); //获取需要统计区划下一级的区划id列表
        if (areaIds != null && areaIds.size() > 0) {
            for (Integer aid : areaIds) {

                //获取区划下数据

                List<Integer> aids = (List<Integer>) cacheService.getCache(String.format(CommonConstant.KEY_AREA, aid));
                if (aids == null || aids.size() == 0) {
                    aids = new ArrayList<>();
                }
                aids.add(aid);

                MetaDTO metaDTO = dataStatMapper.datav_getMoney(datavDTO.getBegin(), datavDTO.getEnd(), aids);
                metaDTO.setAreaId(aid);
                Area areaEntity = (Area) cacheService.getCache(String.format(CommonConstant.KEY_AREA_DATA, aid));
                metaDTO.setAreaStr(areaEntity.getAreaName());
                if (areaEntity != null && org.apache.commons.lang.StringUtils.isNotBlank(areaEntity.getDivisionCode()))
                    metaDTO.setDivisionCode(areaEntity.getDivisionCode());

                //获取该区划下类别的发放情况
                List<MetaDTO> categoryMoneyDataList = dataStatMapper.datav_getCategoryMoneyData(datavDTO.getBegin(), datavDTO.getEnd(), aids);
                if (categoryMoneyDataList != null && categoryMoneyDataList.size() > 0) {
                    List<Points> pointsList = new ArrayList<>();
                    Points points1 = new Points(), points2 = new Points();
                    List<Point> pointList11 = new ArrayList<>(), pointList12 = new ArrayList<>();
                    for (MetaDTO m : categoryMoneyDataList) {
                        pointList11.add(new Point(m.getProjectCategoryName(), m.getGrantTotal().doubleValue()));
                        pointList12.add(new Point(m.getProjectCategoryName(), m.getGrantMoney().doubleValue()));

                    }
                    points1.setName("人次");
                    points1.setPointList(pointList11);

                    points2.setName("金额");
                    points2.setPointList(pointList12);

                    pointsList.add(points1);
                    pointsList.add(points2);

                    metaDTO.setCategoryDataForArea(pointsList);
                }

                areaData.add(metaDTO);
            }
        }
        datavDTO.setAreaData(areaData);

        //第二排，左侧，近3年资金类别占比分析，饼状图
        nowYear = DateUtil.getYear(DateUtil.getCurrentTime());
        beginYear = 2015;
        List<Points> categoryYearData = new ArrayList<>();
        while (beginYear <= nowYear) {
            List<MetaDTO> metaDTOList1 = dataStatMapper.datav_getCategoryYearDataByYear(beginYear);
            Points points = new Points();
            points.setName(String.valueOf(beginYear));
            List<Point> list = new ArrayList<>();
            if (metaDTOList1 != null) {
                for (MetaDTO metaDTO : metaDTOList1) {
                    list.add(new Point(metaDTO.getProjectCategoryName(), metaDTO.getGrantMoney().doubleValue()));
                }
                points.setPointList(list);
            }
            beginYear++;
            categoryYearData.add(points);
        }
        datavDTO.setCategoryYearData(categoryYearData);

//        //第二排，中间，当前发放情况
//        List<MetaDTO> monthData = dataStatMapper.datav_getMoneyGroupByMonth(areaIdsWithChild);
//        datavDTO.setMonthData(monthData);
//
//        //第二排，右侧，受益人群，性别占比
//        List<MetaDTO> genderData = dataStatMapper.datav_getGenderStat(datavDTO.getBegin(), datavDTO.getEnd(), areaIdsWithChild);
//        datavDTO.setGenderData(genderData);

        return datavDTO;
    }


    @Autowired
    private RegisterSuccessMapperExt registerSuccessMapperExt;

    @Autowired
    private DataAreaYearMapper dataAreaYearMapper;

    @Autowired
    private DataCategoryYearMapper dataCategoryYearMapper;

    @Autowired
    private ProjectCategoryMapperExt projectCategoryMapperExt;


    //统计
    public boolean statDatavDataToMysql(String divisionCode) {

        AreaDTO areaDTO = areaManager.getByDivisionCode(divisionCode);
        int areaId = areaDTO.getAreaId();
        int year = DateUtil.getYear(DateUtil.getCurrentTime());

        try {
            List<Integer> areaIds = areaManager.getChildrenAreaIds(areaId, false); //获取需要统计区划下一级的区划id列表
            if (areaIds != null && areaIds.size() > 0) {
                for (Integer aid : areaIds) {

                    Area area = (Area) cacheService.getCache(String.format(CommonConstant.KEY_AREA_DATA, aid));

                    if (area.getAreaName().equals("西宁市学校") || org.apache.commons.lang.StringUtils.isBlank(area.getDivisionCode()))
                        continue;

                    //获取区划下数据
                    List<Integer> aids = (List<Integer>) cacheService.getCache(String.format(CommonConstant.KEY_AREA, aid));

                    Double money = dataStatMapper.datav_getMoneySumByAreaYear(aids, year);
                    DataAreaYear entity = new DataAreaYear();
                    entity.setAreaName(area.getAreaName());
                    entity.setAreaId(area.getAreaId());
                    entity.setDivisionCode(area.getDivisionCode());
                    entity.setMoney(new BigDecimal(money));
                    entity.setYear(year);
                    entity.setUpdateTime(DateUtil.getCurrentTime());

                    DataAreaYearExample example = new DataAreaYearExample();
                    DataAreaYearExample.Criteria criteria = example.createCriteria();
                    criteria.andYearEqualTo(year);
                    criteria.andAreaIdEqualTo(aid);

                    List<DataAreaYear> list = dataAreaYearMapper.selectByExample(example);
                    if (list != null && list.size() > 0) {
                        dataAreaYearMapper.updateByExample(entity, example);
                    } else {
                        dataAreaYearMapper.insert(entity);
                    }


                }
            }

            //获取所有的项目类别
            ProjectCategoryExample projectCategoryExample = new ProjectCategoryExample();
            ProjectCategoryExample.Criteria projectCategoryCriteria = projectCategoryExample.createCriteria();
            projectCategoryCriteria.andIsDeleteEqualTo(false);
            projectCategoryCriteria.andProjectCategoryNameNotEqualTo("历史分类");

            List<ProjectCategory> projectCategoryList = projectCategoryMapperExt.selectByExample(projectCategoryExample);
            if (projectCategoryList != null && projectCategoryList.size() > 0) {
                List<Integer> areaIdsWithChild = (List<Integer>) cacheService.getCache(String.format(CommonConstant.KEY_AREA, areaId));
                if (areaIdsWithChild == null || areaIdsWithChild.size() == 0) {
                    areaIdsWithChild = new ArrayList<>();
                }
                areaIdsWithChild.add(areaId);
                for (ProjectCategory projectCategory : projectCategoryList) {
                    //循环所有的项目分类，获取该分类下所有登记记录的金额汇总
                    Double money = dataStatMapper.datav_getMoneySumByCategoryYear(areaIdsWithChild, year, projectCategory.getProjectCategoryId());

                    DataCategoryYear entity = new DataCategoryYear();
                    entity.setCategoryName(projectCategory.getProjectCategoryName());
                    entity.setCategoryId(projectCategory.getProjectCategoryId());
                    entity.setMoney(new BigDecimal(money));
                    entity.setYear(year);
                    entity.setUpdateTime(DateUtil.getCurrentTime());

                    DataCategoryYearExample example = new DataCategoryYearExample();
                    DataCategoryYearExample.Criteria criteria = example.createCriteria();
                    criteria.andYearEqualTo(year);
                    criteria.andCategoryIdEqualTo(projectCategory.getProjectCategoryId());

                    List<DataCategoryYear> list = dataCategoryYearMapper.selectByExample(example);
                    if (list != null && list.size() > 0) {
                        dataCategoryYearMapper.updateByExample(entity, example);
                    } else {
                        dataCategoryYearMapper.insert(entity);
                    }
                }
            }
        } catch (Exception ex) {
            logger.error(ex.getMessage());
            ex.printStackTrace();
            return false;
        }
        return true;
    }

    private void buildSearch(ReportSearchDTO searchDTO) {

        //项目分类
        if (searchDTO.getProjectCategoryIds() == null || searchDTO.getProjectCategoryIds().size() == 0) {
            searchDTO.setProjectCategoryIds(projectCategoryManager.allIds());
        }

        //项目id
        searchDTO.setProjectIds(projectManager.getProjectIdsByCategoryIds(searchDTO.getProjectCategoryIds(), searchDTO.getProjectIds()));

        //区划id
        Integer areaId = 0;
        if (searchDTO != null && searchDTO.getAreaIds() != null && searchDTO.getAreaIds().size() > 0) {
            areaId = searchDTO.getAreaIds().get(0);
        }
        List<Integer> areaIds = (List<Integer>) cacheService.getCache(String.format(CommonConstant.KEY_AREA, areaId));
        if (areaIds == null) areaIds = new ArrayList<>();
        areaIds.add(areaId);
        searchDTO.setAreaIds(areaIds);

        //状态id
        if (searchDTO.getStates() == null) {
            searchDTO.setStates(ProjectRegisterEn.getAll());
        }
    }

    private void buildAreaSearch(ReportSearchDTO searchDTO) {

        //区划id
        Integer areaId = 0;
        if (searchDTO != null && searchDTO.getAreaIds() != null && searchDTO.getAreaIds().size() > 0) {
            areaId = searchDTO.getAreaIds().get(0);
        }
        List<Integer> areaIds = (List<Integer>) cacheService.getCache(String.format(CommonConstant.KEY_AREA, areaId));
        if (areaIds == null) areaIds = new ArrayList<>();
        areaIds.add(areaId);
        searchDTO.setAreaIds(areaIds);

    }

}
